package com.itheima.service.impl;

import com.itheima.mapper.MemberMapper;
import com.itheima.mapper.OrderMapper;
import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.vo.OrderMobileVO;
import com.itheima.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Map;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderSettingMapper orderSettingMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 提交预约订单
     *
     * @param map
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String submitOrder(Map<String, Object> map) {
        // 验证码校验
        if(map.get("validateCode") == null || !map.get("validateCode").equals(redisTemplate.opsForValue().get("validateCode:" + map.get("telephone")))){
            log.info("验证码校验失败");
            return "验证码校验失败";
        }else {
            log.info("验证码校验成功");
        }

        // 查询是否还有剩余预约名额
        LocalDate orderDate = LocalDate.parse((String) map.get("orderDate"));
        OrderSetting os = orderSettingMapper.selectByDay(orderDate);
        if(os == null){
            log.info("该日期没有预约名额");
            return "该日期没有预约名额";
        }else if(os.getReservations() >= os.getNumber()){
            log.info("该日期预约名额已满");
            return "该日期预约名额已满";
        }else {
            log.info("该日期有剩余预约名额, 记录一次预约");
            os.setReservations(os.getReservations() + 1);
        }

        // 处理数据
        String idCard = (String) map.get("idCard");
        log.info("idCard:{}", idCard);
        // 1.查询会员，如不存在则新增该会员信息，需要返回主键id
        Member member = memberMapper.selectByIdCard(idCard);
        log.info("member:{}", member);
        if(member == null){
            log.info("会员不存在，数据库需要保存该信息");
            member = new Member();
            member.setIdCard(idCard);
            member.setFileNumber("unknown");
            member.setName((String) map.get("name"));
            member.setSex(Integer.parseInt((String) map.get("sex")) == 1 ? "男" : "女");
            member.setPhoneNumber((String) map.get("telephone"));
            member.setRegTime(LocalDate.now());
            member.setPassword("123456");
            log.info("member:{}", member);
            if(memberMapper.insert(member) < 1){
                throw new RuntimeException("新增会员失败");
            }
        }
        Order order = new Order();
        order.setMemberId(member.getId());
        order.setOrderDate(LocalDate.parse((String) map.get("orderDate")));
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setOrderType(Order.ORDERTYPE_WEIXIN);
        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));
        log.info("order:{}", order);
        orderMapper.insert(order);
        // 修改预约记录
        orderSettingMapper.updateReservationByDate(os);
        return order.getOrderDate().getDayOfMonth() + "";
    }

    /**
     * 根据id查询预约信息
     *
     * @param id
     * @return
     */
    @Override
    public OrderMobileVO findById(Integer id) {
        return orderMapper.selectOrderVOById(id);
    }
}
